class Solution(object):
    def closedIsland(self, grid):
        m = len(grid)
        n = len(grid[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0:
                    flag = True
                    now = {(i, j)}
                    while now:
                        x, y = now.pop()
                        for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                            if 0 <= ux < m and 0 <= uy < n:
                                if grid[ux][uy] == 0:
                                    now.add((ux, uy))
                                    grid[ux][uy] = 2
                            else:
                                flag = False
                    ans += flag
        return ans
